#-*- coding: latin-1 -*-
'''
Created on 31.10.2013

@author: Hualiang Qi
'''

from converterexception import ArabicTooBigException, ArabicInvalidException
 
#http://en.wikipedia.org/wiki/Roman_numerals
# BASE_NUMBER = {1:"I", 5:"V", 10:"X", 50:"L", 100:"C", 500:"D", 1000: "M"}
BASE_NUMBER = [(1000, "M"), (500, "D"), (100, "C"), (50, "L"), (10, "X"),
               (5, "V"), (1, "I")]
BASE_NUMBER_DICT = dict(BASE_NUMBER)
ARABIC_SEVEN, _ROMAN_SEVER = zip(*BASE_NUMBER)
MAX_CONVERTABLE_ARABIC_NUMBER =3999

def arabic_to_roman(arabic_number):
    '''
    
    return the corresponding roman number string for a given arabic number.

    :param arabic_number:
    '''
    try:
        arabic_number = int(arabic_number)
    except Exception as _e:
        raise ArabicInvalidException()
 
    if arabic_number == 0:
        raise ArabicInvalidException()
    elif arabic_number > MAX_CONVERTABLE_ARABIC_NUMBER:
        raise ArabicTooBigException()
    
    if arabic_number in ARABIC_SEVEN:
        return BASE_NUMBER_DICT[arabic_number]
    
    roman_number_string = []
    digits_counter = len(ARABIC_SEVEN)
    check_from = 0
    while (arabic_number):
        for index in range(check_from, digits_counter, 2):
            if arabic_number > ARABIC_SEVEN[index]:
                break
            check_from = +2

        upper_limit = ARABIC_SEVEN[index-2]
        middle = ARABIC_SEVEN[index-1]
        lower_limit = ARABIC_SEVEN[index]
        residual, arabic_number = divmod(arabic_number, lower_limit)
        num, remainder = divmod(residual, 5)
        repeatable_sign = BASE_NUMBER_DICT[lower_limit]
        irreatable_sign = BASE_NUMBER_DICT[middle]
        if num == 1:
            if remainder == 4:
                roman_number_string.append(repeatable_sign + BASE_NUMBER_DICT[upper_limit])
            else:
                roman_number_string.append(irreatable_sign + repeatable_sign*remainder)
        else:
            if remainder == 4:
                roman_number_string.append(repeatable_sign + irreatable_sign)
            else:
                roman_number_string.append(repeatable_sign*remainder)

    return "".join(roman_number_string)

if __name__ == "__main__":
    pass